import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  Image,
  Dimensions,
  StatusBar,
  KeyboardAvoidingView,
  TextInput,
  TouchableWithoutFeedback,
  Alert,
  ActivityIndicator,
} from 'react-native';
import {Actions} from 'react-native-router-flux';
import CommonStyles from '../../common/styles';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import api from '../../common/api';
import {AlbumView, Overlay, PullPicker} from 'teaset';
import Toast from 'react-native-easy-toast';
import {Avatar, Divider } from 'react-native-elements';
import Button from 'antd-mobile/lib/button';
import Config from '../../common/config';

const {width, height} = Dimensions.get('window');

export default class Detail extends React.Component {
  constructor(props) {
    console.log("Detail: ", props);
    super(props);
    this.state = {
      orderType: null,
      params: props.router_params,
      page: 1,
      loading: false,
      loadingMore: false,
      hasMore: true,
      list: [],
      include_root_comment: true,
      rootCommentInfo: props.router_params.comment,
      parentComment: props.router_params.comment,
      parentCommentUserName: props.router_params.comment.user.data.name,
      inputText: "",
      isKeyboardShown: false,
    }
  }

  images = [
    require('../../images/1.jpg'),
    require('../../images/2.jpg'),
    require('../../images/3.jpg'),
    {uri: "http://ot8uv8omp.bkt.clouddn.com/2.png"},
  
  ]

  orderTypes = [
    '综合排序',
    '按回复时间排序',
    '按发表时间排序'
  ]

  selectOrderType() {
    console.log("selectOrderType");
    PullPicker.show(
      '选择排列顺序',
      this.orderTypes,
      this.state.orderType || 0,
      (item, index) => this.setState({orderType: index})
    );
  }


  renderSectionHeader({section}) {
    if (section.content == "forum_info") {
      return null;
    }
    return (
      <View style={[CommonStyles.container]}>
        <View style={[CommonStyles.row, styles.topicFilter]}>
          <Text style={styles.topicFilterActive}>全部</Text>
      
            <TouchableOpacity style={[CommonStyles.row, styles.topicFilterOrder]} onPress={() => this.selectOrderType()}>
              <Text>回复时间排序</Text>
              <Icon name="chevron-down" size={20}/>
            </TouchableOpacity>
       
        </View>
      </View>
     
    )
  }

  viewImage(index) {
    console.log("viewImage: " + index);
    let overlayView = (
      <Overlay.PopView
        style={{}}
        containerStyle={{flex: 1}}
        overlayOpacity={1}
        type='custom'
        customBounds={{x: 10, y: 10, width: 200, height: 400}}
        ref={v => this.fullImageView = v}
      >
        <AlbumView
          style={{flex: 1}}
          control={true}
          images={this.images}
          defaultIndex={1}
          onPress={() => this.fullImageView && this.fullImageView.close()}
          />
        <StatusBar animated={false} hidden={true} />
      </Overlay.PopView>
    );
    Overlay.show(overlayView);
  }

  componentDidMount() {
    this.setState({
      loading: true,
    }, () => {
      this.fetchComments();
    });
  }

  onRefresh() {
    if (this.state.loading) {
      console.log("loading...");
      return;
    }
    this.setState({
      loading: true,
      page: 1,
      hasMore: true,
    }, () => {
      this.fetchComments();
    })
  }

  fetchComments() {
    var self = this;
    let queryString = "root_comment_key=" + this.state.params.comment.key + "&page=" + this.state.page;
    if (this.state.include_root_comment)
    {
      queryString += "&include_root_comment=1";
    }
    api.listCommentComment(queryString)
    .then((response) => {
      console.log(response);
      self.setState({
        loading: false,
        loadingMore: false,
      });
      if (response.ret == 0) {
        if (response.data.pagination.count == 0) {
          console.log("count = 0, hasMore = false");
          self.setState({hasMore: false});
          return;
        }
        if (response.data.pagination.current_page == 1) {
          var newList = response.data.list;
        } else {
          var newList = [...self.state.list, ...response.data.list];
        }
        let newState = {
          list: newList,
          pagination: response.data.pagination,
          page: response.data.pagination.current_page + 1,
          include_root_comment: false,
        }
        if (response.data.root_comment) {
          newState.rootCommentInfo = response.data.root_comment.data;
        }
        self.setState(newState);
      } else {
        Toast.show(response.msg);
      }
      
    })
  }

  onItemPress(item) {
    console.log("onItemPress: ", item);
    this.setState({
      parentComment: item,
      parentCommentUserName: item.user.data.name + "--" + item.id,
    })
  }

  renderItem = ({item, index}) => {
    return (
      <TouchableWithoutFeedback    
        onPress={() => {this.onItemPress(item)}}
      >
        <View style={[CommonStyles.container, styles.commentCommentItem]}>
        <Text>
          {
            item.user.data.name + ": " + 
            (item.parentComment ? "回复 " + item.parentComment.data.user.data.name + ": " : "") + 
            item.detail.data.content[0].data.text
          }
        </Text>
        </View>
      </TouchableWithoutFeedback>
    )
  }

  itemSeparator = () => {
    return null;
    return (
      <View style={styles.itemSeparator}></View>
    )
  }

  flatListHeaderComponent() {
    return (
      <View style={[CommonStyles.container, styles.itemWrap]}>
        <View style={[CommonStyles.row, styles.topicHeader]}>
          {
            this.state.rootCommentInfo.user ? 
            <Avatar small rounded source={{uri: this.state.rootCommentInfo.user.data.avatar}} />
            : null
          }
          <View>
            <Text style={[styles.nickname]}>{this.state.rootCommentInfo.user ? this.state.rootCommentInfo.user.data.name : ""}</Text>
            <View style={[CommonStyles.row]}>
                <Text style={[styles.updateTime]}>{this.state.rootCommentInfo.created_at_human}</Text>
                <View style={[CommonStyles.row, styles.countWrap]}>
                <Icon name="comment-outline" />
                <Text style={styles.viewCount}>100</Text>
                </View>
                <View style={[CommonStyles.row, styles.countWrap]}>
                <Icon name="view-week" />
                <Text style={styles.commentCount}>120</Text>
                </View>
            </View>
          </View>
        </View>
        <View style={styles.itemContentWrap}>
        {this.state.rootCommentInfo.detail ? this.state.rootCommentInfo.detail.data.content.map((_content, i) => {
          if (_content.type == "text") {
            return (
              
                <View style={[styles.contentWrap]} key={i}>
                  <Text>{_content.data.text}</Text>
                </View>
            )
          } else if (_content.type == "image") {
            return (
              <TouchableOpacity onPress={() => this.viewImage(1)} key={i}>
                <Image 
                  source={{uri: Config.attachment_base_uri + _content.data.key}} 
                  style={[styles.detailAttachmentImage, {width: width - 30}]} 
                />
              </TouchableOpacity>
            )
          }
        }) : null}
        </View>
      </View>
    )
  }

  createComment() {
    let data = {
      tid: this.state.rootCommentInfo.tid,
      content: this.state.inputText,
      pid: this.state.parentComment.id,
    }
    console.log(data);
    api.createComment(data).then(response => {
      console.log(response);
      if (response.ret == 0) {
        this.setState({
          inputText: "",
          hasMore: true,
        }, () => {
          // let textInput = this.refs["create_comment_text_input"];
          this.refs.create_comment_text_input.focus();
          this.refs.create_comment_text_input.clear();

          // textInput.blur();
          // this.refs.toast.show(response.msg);
        });
      } else {
        Alert.alert(response.msg);
      }
      
    })
  }

  renderFooter() {
    if (!this.state.loadingMore) {
      return null;
    }
    return (
      <View style={styles.loadingMore}>
        <ActivityIndicator animating size="large" />
      </View>
    )
  }

  onEndReached({distanceFromEnd}) {
    console.log("onEndReached...", distanceFromEnd);
    if (this.state.loadingMore) {
      console.log("onEndReached...loadingMore...");
      return;
    }
    if (this.state.hasMore) {
      this.setState({
        loadingMore: true
      }, () => {
        this.fetchComments();
      })
      
    }
    
  }

  render() {
    return (
      <KeyboardAvoidingView style={{flex: 1}} behavior="padding" keyboardVerticalOffset={60}>
        <FlatList
          ListHeaderComponent={() => this.flatListHeaderComponent()}
          renderItem={this.renderItem}
          data={this.state.list}
          refreshing={this.state.loading}
          onRefresh={() => this.onRefresh()}
          onEndReachedThreshold={0.1}
          onEndReached={(info) => this.onEndReached(info)}
          ListFooterComponent={() => this.renderFooter()}
        />
        <View style={[CommonStyles.row, styles.textInputWrap]} >
          <TextInput 
            style={styles.textInput} 
            multipline={true} 
            underlineColorAndroid="transparent" 
            placeholder={"回复 " + this.state.parentCommentUserName}
            onChangeText={text => this.setState({inputText: text})}
            ref="create_comment_text_input"
          />
          <TouchableOpacity style={styles.submitBtn} onPress={() => this.createComment()}>
            <Text style={{fontSize: 18}}>提交</Text>
          </TouchableOpacity>
        </View>
        <Toast ref="toast" position="center"/>
     </KeyboardAvoidingView>
    )
  }
}

var styles = StyleSheet.create({
  sectionTopAction: {
    paddingTop: 24,
    justifyContent: "space-between",
    alignItems: "center",
  },
  pagetTitleLeft: {
    alignSelf: "flex-start"
  },
  sectionHeaderWrapper: {
    paddingBottom: 15,
    marginBottom: 5,
  },
  sectionHeader: {
    alignItems: "center",
    justifyContent: "space-between",
  },
  forumDesc: {
    marginLeft: 10,
  }, 
  forumInfo: {
    alignItems: "center",
  },
  forumCover: {

  },
  nickname: {
    marginBottom: 5
  },
  updateTime: {
    fontSize: 12,
  },
  viewCount: {
    fontSize: 12,
  },
  commentCount: {
    fontSize: 12,
  },
  forumName: {
    fontSize: 20,
    marginBottom: 5
  },
  forumStat: {
    marginRight: 10,
  },
  followBtn: {
    width: 50,
    height: 30,
  },
  divider: {
    marginTop: 10,
    marginBottom: 10,
  },

  flatList: {
    marginTop: 4,
  },

  itemWrap: {
    marginBottom: 3,
    paddingTop: 10,
    paddingBottom: 10,
  },
  itemContentWrap: {
   
  },
  itemSeparator: {
    display: "flex",
    height: 1,
    backgroundColor: "#ddd"
  },
  arrow: {
    position: "absolute",
    right: 0
  },
  countWrap: {
    alignItems: "center",
    marginLeft: 5,
  },
  contentWrap: {
    paddingTop: 10,
    paddingBottom: 10,

  },
  floorWrap: {
    paddingLeft: 80,
  },
  attachmentImage: {
    //marginRight: 5,
    height: 100,
    width: (width - 30) / 2,
  },
  detailAttachmentImage: {
    height: 100,
    width: (width - 30) / 2,
  },
  topicFilter: {
    justifyContent: "space-between",
    alignItems: "center",
    paddingTop: 5,
    paddingBottom: 5,
    borderBottomColor: "#eee",
    borderBottomWidth: 1,
  },
  topicFilterActive: {
    borderBottomWidth: 1,
    borderBottomColor: "#000",
  },
  topicFilterOrder: {
    alignItems: "center",
  },
  mainFloorInfoHeader: {
    justifyContent: "space-between"
  },
  commentCommentWrap: {
    backgroundColor: "#eee",
    padding: 10,
    marginTop:10,
  },
  commentCommentContent: {
    flexWrap: "wrap",
    marginBottom: 10,
  },
  textInputWrap: {
    //height: 40,
  },
  textInput: {
    width: "88%",
    padding: 10,
    textAlignVertical: "top",
    backgroundColor: "#eee",
  },
  submitBtn: {
    display: "flex",
    width: "12%",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "gray",
  },
  commentCommentItem: {
    paddingTop: 5,
    paddingBottom: 5,
  }
  
})
